package com.ktjiaoyu.ktmall.dao.impl;

import com.ktjiaoyu.ktmall.dao.BaseDao;
import com.ktjiaoyu.ktmall.dao.UserDao;
import com.ktjiaoyu.ktmall.entity.User;

import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl extends BaseDao implements UserDao {

    @Override
    public User findByUsername(String username) {
        String sql = "SELECT `id`, `username`, `password`, `nickname`, `avatar`, `phone`, `email`, `gender`, `birthday`, `register_time`, `last_login_time`, `status`, `is_deleted` FROM kt_user WHERE username = ? AND is_deleted = 0";
        try {
            return executeQuery(sql, rs -> {
                try {
                    if (rs.next()) {
                        return readRs(rs);
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                return null;
            }, username);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public User findById(String id) {
        String sql = "SELECT `id`, `username`, `password`, `nickname`, `avatar`, `phone`, `email`, `gender`, `birthday`, `register_time`, `last_login_time`, `status`, `is_deleted` FROM kt_user WHERE id = ? AND is_deleted = 0";
        try{
            return executeQuery(sql, rs -> {
                try {
                    if (rs.next()) {
                        return readRs(rs);
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                return null;
            }, id);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }

    }

    private User readRs(ResultSet rs) throws SQLException{
        User user = new User();
        user.setId(rs.getString("id"));
        user.setUsername(rs.getString("username"));
        user.setPassword(rs.getString("password"));
        user.setNickname(rs.getString("nickname"));
        user.setAvatar(rs.getString("avatar"));
        user.setPhone(rs.getString("phone"));
        user.setEmail(rs.getString("email"));
        user.setGender(rs.getInt("gender"));
        user.setBirthday(rs.getDate("birthday"));
        user.setRegisterTime(rs.getDate("register_time"));
        user.setLastLoginTime(rs.getDate("last_login_time"));
        user.setStatus(rs.getInt("status"));
        user.setIsDeleted(rs.getInt("is_deleted"));
        return user;
    }


}
